<template>
  <div class="app-container">
    <!-- 搜索和新增区域 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input v-model="queryParams.warehouseName" placeholder="请输入仓库名称" clearable @clear="handleSearch"
            @keyup.enter="handleSearch">
            <template #append>
              <el-button icon="Search" @click="handleSearch" />
            </template>
          </el-input>
        </el-col>
      </el-row>
    </el-card>

    <!-- 仓库表格 -->
    <el-card class="mt-1">
      <el-button type="primary" @click="showAddDialog" icon="Plus">新增仓库</el-button>
      <el-table class="mt-2" :data="warehouseList" border v-loading="loading" :cell-style="{ textAlign: 'center' }"
        :header-cell-style="{ textAlign: 'center', fontWeight: 'bold' }">
        <el-table-column prop="warehouseName" label="仓库名称" />
        <el-table-column prop="warehouseNumber" label="编号" />
        <el-table-column prop="warehouseType" label="类型" />
        <el-table-column prop="location" label="位置" />
        <el-table-column prop="capacity" label="容量(m³)" />
        <el-table-column prop="contactPerson" label="负责人" />
        <el-table-column prop="contactNumber" label="负责人电话" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="mt-2">
        <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 新增仓库对话框 -->
    <el-dialog v-model="addDialogVisible" title="新增仓库" width="50%" :close-on-click-modal="false">
      <el-form :model="addForm" label-width="120px" :rules="rules" ref="addFormRef">
        <el-form-item label="仓库名称" prop="warehouseName">
          <el-input v-model="addForm.warehouseName" placeholder="请输入仓库名称" />
        </el-form-item>
        <el-form-item label="编号" prop="warehouseNumber">
          <el-input v-model="addForm.warehouseNumber" placeholder="请输入编号" />
        </el-form-item>
        <el-form-item label="类型" prop="warehouseType">
          <el-select v-model="addForm.warehouseType" placeholder="请选择类型" style="width: 100%">
            <el-option v-for="item in warehouseTypeOptions" :key="item.dictValue" :label="item.dictLabel"
              :value="item.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="位置" prop="location">
          <el-input v-model="addForm.location" placeholder="请输入位置信息" />
        </el-form-item>
        <el-form-item label="容量(m³)" prop="capacity">
          <el-input-number v-model="addForm.capacity" :min="0" :step="10" style="width: 100%" />
        </el-form-item>
        <el-form-item label="负责人" prop="contactPerson">
          <el-input v-model="addForm.contactPerson" placeholder="请输入负责人姓名" />
        </el-form-item>
        <el-form-item label="负责人电话" prop="contactNumber">
          <el-input v-model="addForm.contactNumber" placeholder="请输入负责人电话" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAdd">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑仓库对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑仓库" width="50%" :close-on-click-modal="false">
      <el-form :model="editForm" label-width="120px" :rules="rules" ref="editFormRef">
        <el-form-item label="仓库名称" prop="warehouseName">
          <el-input v-model="editForm.warehouseName" placeholder="请输入仓库名称" />
        </el-form-item>
        <el-form-item label="编号" prop="warehouseNumber">
          <el-input v-model="editForm.warehouseNumber" placeholder="请输入编号" />
        </el-form-item>
        <el-form-item label="类型" prop="warehouseType">
          <el-select v-model="editForm.warehouseType" placeholder="请选择类型" style="width: 100%">
            <el-option v-for="item in warehouseTypeOptions" :key="item.dictValue" :label="item.dictLabel"
              :value="item.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="位置" prop="location">
          <el-input v-model="editForm.location" placeholder="请输入位置信息" />
        </el-form-item>
        <el-form-item label="容量(m³)" prop="capacity">
          <el-input-number v-model="editForm.capacity" :min="0" :step="10" style="width: 100%" />
        </el-form-item>
        <el-form-item label="负责人" prop="contactPerson">
          <el-input v-model="editForm.contactPerson" placeholder="请输入负责人姓名" />
        </el-form-item>
        <el-form-item label="负责人电话" prop="contactNumber">
          <el-input v-model="editForm.contactNumber" placeholder="请输入负责人电话" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmEdit">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getWarehouseTypeList,
  getWarehouseList,
  getWarehouseDetail,
  addWarehouse,
  updateWarehouse,
  deleteWarehouse
} from '@/api/prod_operate/sys_setting/basic/warehouse_setup'

// 加载状态
const loading = ref(false)

// 仓库类型选项
const warehouseTypeOptions = ref([])

// 仓库列表数据
const warehouseList = ref([])

// 总记录数
const total = ref(0)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  warehouseName: undefined
})

// 新增表单
const addForm = reactive({
  warehouseName: '',
  warehouseNumber: '',
  warehouseType: '',
  location: '',
  capacity: 0,
  contactPerson: '',
  contactNumber: ''
})

// 编辑表单
const editForm = reactive({
  warehouseId: '',
  warehouseName: '',
  warehouseNumber: '',
  warehouseType: '',
  location: '',
  capacity: 0,
  contactPerson: '',
  contactNumber: ''
})

// 对话框控制
const addDialogVisible = ref(false)
const editDialogVisible = ref(false)

// 表单引用
const addFormRef = ref(null)
const editFormRef = ref(null)

// 表单验证规则
const rules = reactive({
  warehouseName: [
    { required: true, message: '请输入仓库名称', trigger: 'blur' }
  ],
  warehouseNumber: [
    { required: true, message: '请输入编号', trigger: 'blur' }
  ],
  warehouseType: [
    { required: true, message: '请选择类型', trigger: 'change' }
  ],
  location: [
    { required: true, message: '请输入位置信息', trigger: 'blur' }
  ],
  capacity: [
    { required: true, message: '请输入容量', trigger: 'blur' }
  ],
  contactPerson: [
    { required: true, message: '请输入负责人姓名', trigger: 'blur' }
  ],
  contactNumber: [
    { required: true, message: '请输入负责人电话', trigger: 'blur' }
  ]
})

// 初始化数据
const initData = async () => {
  try {
    loading.value = true

    // 获取仓库类型列表
    const typeRes = await getWarehouseTypeList()
    warehouseTypeOptions.value = typeRes.data

    // 获取仓库列表
    await fetchWarehouseList()
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('初始化数据失败')
  } finally {
    loading.value = false
  }
}

// 获取仓库列表
const fetchWarehouseList = async () => {
  try {
    loading.value = true
    const res = await getWarehouseList(queryParams)
    warehouseList.value = res.rows
    total.value = res.total
  } catch (error) {
    console.error('获取仓库列表失败:', error)
    ElMessage.error('获取仓库列表失败')
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  queryParams.pageNum = 1
  fetchWarehouseList()
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  fetchWarehouseList()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  fetchWarehouseList()
}

// 显示新增对话框
const showAddDialog = () => {
  addForm.warehouseName = ''
  addForm.warehouseNumber = ''
  addForm.warehouseType = ''
  addForm.location = ''
  addForm.capacity = 0
  addForm.contactPerson = ''
  addForm.contactNumber = ''
  addDialogVisible.value = true
}

// 确认新增
const confirmAdd = async () => {
  try {
    await addFormRef.value.validate()

    await addWarehouse(addForm)
    ElMessage.success('新增仓库成功')
    addDialogVisible.value = false
    fetchWarehouseList()
  } catch (error) {
    console.error('新增仓库失败:', error)
    if (error.message) {
      ElMessage.error(error.message)
    }
  }
}

// 处理编辑
const handleEdit = async (row) => {
  try {
    loading.value = true
    const res = await getWarehouseDetail(row.warehouseId)
    Object.assign(editForm, res.data)
    editDialogVisible.value = true
  } catch (error) {
    console.error('获取仓库详情失败:', error)
    ElMessage.error('获取仓库详情失败')
  } finally {
    loading.value = false
  }
}

// 确认编辑
const confirmEdit = async () => {
  try {
    await editFormRef.value.validate()

    await updateWarehouse(editForm)
    ElMessage.success('修改仓库成功')
    editDialogVisible.value = false
    fetchWarehouseList()
  } catch (error) {
    console.error('修改仓库失败:', error)
    if (error.message) {
      ElMessage.error(error.message)
    }
  }
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该仓库吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteWarehouse(row.warehouseId)
      ElMessage.success('删除成功')
      fetchWarehouseList()
    } catch (error) {
      console.error('删除仓库失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 初始化
onMounted(() => {
  initData()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}

.el-select {
  width: 100%;
}

.el-table {
  margin-top: 20px;
}

.el-input-number {
  width: 100%;
}
</style>